from collections.abc import Generator
from typing import Annotated

from fastapi import Depends

from sqlmodel import Field, Session, SQLModel, create_engine, select

from app.core.config import settings
from app.core.security import get_password_hash
from app.models.system_admin import SystemAdmin

engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI), echo=True)


def get_db() -> Generator[Session, None, None]:
    with Session(engine) as session:
        yield session


SessionDep = Annotated[Session, Depends(get_db)]


def create_db_and_tables():
    SQLModel.metadata.create_all(engine)


def init_db(session: Session) -> None:
    # Tables should be created with Alembic migrations
    # But if you don't want to use migrations, create
    # the tables un-commenting the next lines
    # from sqlmodel import SQLModel

    # This works because the models are already imported and registered from app.models
    # SQLModel.metadata.create_all(engine)
    user = session.exec(
        select(SystemAdmin).where(SystemAdmin.username == 'admin')
    ).first()
    if not user:
        db_obj = SystemAdmin(
            username='admin',
            password=get_password_hash('123456'),
            is_super=1,
        )
        session.add(db_obj)
        session.commit()
        session.refresh(db_obj)
